#include "gameboard.h"
#include <QGraphicsRectItem>
#include <QGraphicsSimpleTextItem>
#include <QLinearGradient>

GameBoard::GameBoard(QWidget *parent)
    : QGraphicsView(parent),
    m_scene(new QGraphicsScene(this)),
    m_visiblePlayers(2)
{
    // 初始化场景和视图
    setScene(m_scene);
    setRenderHint(QPainter::Antialiasing);
    setMinimumSize(BOARD_SIZE * GRID_SIZE + 20, BOARD_SIZE * GRID_SIZE + 20);
    setStyleSheet("border: 2px solid #607D8B; border-radius: 8px;");

    // 初始化玩家棋子
    const QColor colors[] = {Qt::red, Qt::blue, Qt::green};
    for(int i = 0; i < 3; ++i) {
        m_players[i] = new QGraphicsEllipseItem(0, 0, 40, 40);
        m_players[i]->setBrush(colors[i]);
        m_players[i]->setPen(QPen(Qt::black, 2));
        m_players[i]->setZValue(1);
        m_players[i]->setVisible(i < m_visiblePlayers);
        m_scene->addItem(m_players[i]);
    }

    initializeSpecialGrids();
    createGrid();
    reset();
}

// 移动玩家到指定位置（0-80）
void GameBoard::movePlayer(int playerId, int position)
{
    if(playerId < 0 || playerId >= 3) return;

    position = qBound(0, position, 80);
    m_players[playerId]->setPos(calculatePosition(position));
}

// 重置所有玩家到起点
void GameBoard::reset()
{
    for(int i = 0; i < m_visiblePlayers; ++i) {
        movePlayer(i, 0);
    }
}

// 设置可见玩家数量（2或3）
void GameBoard::setVisiblePlayers(int count)
{
    m_visiblePlayers = qBound(2, count, 3);
    for(int i = 0; i < 3; ++i) {
        m_players[i]->setVisible(i < m_visiblePlayers);
    }
}

// 设置玩家棋子边框颜色
void GameBoard::setPlayerColor(int playerId, const QColor &color)
{
    if(playerId < 0 || playerId >= 3) return;
    m_players[playerId]->setPen(QPen(color, 2));
}

// 查询格子类型
GridType GameBoard::getGridType(int position) const
{
    return m_specialGrids.value(position, Normal);
}

// 计算棋盘坐标（核心算法）
QPointF GameBoard::calculatePosition(int pos) const
{
    const int row = pos / BOARD_SIZE;
    const bool reverseRow = (row % 2 != 0);
    const int col = reverseRow ?
                        (BOARD_SIZE - 1 - (pos % BOARD_SIZE)) :
                        (pos % BOARD_SIZE);

    // 计算中心点坐标（棋子尺寸40x40，格子尺寸60x60）
    const qreal x = col * GRID_SIZE + (GRID_SIZE - 40) / 2.0;
    const qreal y = row * GRID_SIZE + (GRID_SIZE - 40) / 2.0;
    return QPointF(x, y);
}

// 初始化特殊格子配置
void GameBoard::initializeSpecialGrids()
{
    m_specialGrids = {
        {5,  Forward3},    {6,  Backward5},   {7,  ExtraTurn},
        {11, Forward3},    {18, ExtraTurn},   {21, Forward3},
        {22, Backward5},   {29, ExtraTurn},   {35, Forward3},
        {44, Backward5},   {45, BackToStart}, {52, ExtraTurn},
        {58, Backward5},   {63, BackToStart}, {66, TeleportEnd},
        {68, Forward3},    {74, Backward5},   {79, ExtraTurn}
    };
}

// 创建棋盘网格（无addItems错误版本）
void GameBoard::createGrid()
{
    QLinearGradient bgGradient(0, 0, width(), height());
    bgGradient.setColorAt(0, QColor(240, 240, 240));
    bgGradient.setColorAt(1, QColor(200, 200, 200));
    m_scene->setBackgroundBrush(bgGradient);

    // 逐个添加棋盘格子
    for(int row = 0; row < BOARD_SIZE; ++row) {
        for(int col = 0; col < BOARD_SIZE; ++col) {
            const int pos = row * BOARD_SIZE + ((row % 2 == 0) ? col : (BOARD_SIZE - 1 - col));

            // 创建格子矩形
            QGraphicsRectItem* cell = new QGraphicsRectItem(
                col * GRID_SIZE, row * GRID_SIZE, GRID_SIZE, GRID_SIZE);
            cell->setPen(QPen(Qt::gray, 1));
            cell->setBrush(QColor(255, 255, 255, 150));
            m_scene->addItem(cell);

            // 添加位置编号
            QGraphicsSimpleTextItem* numText = new QGraphicsSimpleTextItem(QString::number(pos));
            numText->setPos(col * GRID_SIZE + 5, row * GRID_SIZE + 5);
            numText->setBrush(Qt::darkGray);
            m_scene->addItem(numText);
        }
    }
}
